<?php

namespace Home\Controller;


/**
 * 店铺测试控制器
 *
 */
class TestController extends HomeController
{

    /**
     * 生成测试二维码
     * @param int $id 店铺id
     * @param int $amount 付款金额
     * @param int $type 类型：2=花呗,1=手机网站支付,4=手机网站支付信用卡,5=当面付信用卡
     *
     */
    public function getTestQrcodeUrl($id, $amount, $type = 2)
    {
        $outTradeNo = 'test' . date("YmdHis") . rand(1000, 9999);//2+14+4
        $subject = "测试$outTradeNo";


        $payLogic = new \Home\Logic\PayLogic();
        $kbsh = $payLogic->getAlipayByType($type,$id);

        // 调用预下单接口得到付款二维码
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $qrpay = new \Alipay;

        //预下单  仅支持花呗
        $result = $qrpay->qrpaytest($outTradeNo, $subject, $amount, '', $kbsh);

        if($result->code != 10000) {
            $this->showError($result->sub_msg);
        }

        $erwm = $result->qr_code;
        if ($erwm == '') {
            // 该口碑码不可用
            $payLogic->changeAlipayStatusByType($type,$id,2,'该口碑码不可用,请刷新重试！');
            $this->showError('该口碑码不可用,请刷新重试！');
        }

        $data = [
            'danhao' => $outTradeNo,
            'pay_money' => $amount,
            'pay_time' => time(),
            'seller_id' => $kbsh['user_id'],
            'erwm' => $erwm
        ];

        if($type == 2){
            M('test')->add([
                'danhao' => $outTradeNo,
                'total_amount' => $amount,
                'kbsh_id' => $id,
                'type' => $type
            ]);
        }else{
            M('test')->add([
                'danhao' => $outTradeNo,
                'total_amount' => $amount,
                'alipays_id' => $id,
                'type' => $type
            ]);
        }

        return $data;
    }


    /**
     * 获取测试店铺二维码
     * @param $id
     * @param $amount
     * @param int $type 默认当面付花呗
     */
    public function getTestQrcode($id, $amount,$type = 2)
    {
        $res = $this->getTestQrcodeUrl($id, $amount,$type);
        QRcode($res['erwm']);
    }

    public function getTestQrUrl($id, $amount)
    {
        $res = $this->getTestQrcodeUrl($id, $amount);
        $this->showSuccess('', $res);

    }

    /**
     * 测试二维码当面付回调
     */
    public function huabei_notify()
    {

        file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试二维码当面付回调异步回调数据：' . json_encode($_POST) . PHP_EOL, FILE_APPEND);

        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
            // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；3、将口碑商户扣取费率后的余额转入企业支付宝
            $danhao = $_POST['out_trade_no'];
            $one = M('test')->where(['danhao' => $danhao])->find();

            if ($one['status'] == 1) {
                echo success;
            } else {
                $trade_no = $_POST['trade_no'];
                $money = $_POST['total_amount'];
                $seller_id = $_POST['seller_id'];//卖家支付宝用户号,以2088开头的纯16位数字
                $buyer_id = $_POST['buyer_id'];//买家支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字

                $res = M('test')->where(['danhao' => $danhao])->save([
                    'status' => 1,
                    'createtime' => time(),
                    'trade_no' => $trade_no,
                    'buyer_id' => $buyer_id,
                    'seller_id' => $seller_id
                ]);
                $this->settle($danhao);
                echo success;
            }
        }
    }

    /**
     * 分账
     */
    public function settle($danhao){
        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
        $qrpay = new \Alipay;
        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号
        $test = M('test')->where(['danhao' => $danhao])->find();

        if($test['type'] == 2){
            $value_id = $test['kbsh_id'];
        }else{
            $value_id = $test['alipays_id'];
        }

        $payLogic = new \Home\Logic\PayLogic();
        $adata = $payLogic->getAlipayByType($test['type'],$value_id);

        $app_auth_token = '';
        $royalty_parameters = [
            'trans_out' => "{$test['seller_id']}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $test['buyer_id'], //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => floor($test['total_amount']*0.7*100)/100,   //分账出去的金额
            'desc' => '测试分账',
        ];
        $result = $qrpay->settle($out_request_no, $test['trade_no'], $royalty_parameters, $app_auth_token, $adata);
        file_put_contents("test.txt", date('Y-m-d H:i:s') . '分账结果：' . json_encode($result) . PHP_EOL, FILE_APPEND);

        $resultCode = $result->code;

        if(!empty($resultCode)&&$resultCode == 10000){
            $data = [
                'code' => 1,
                'msg' => '分账成功',
                'data' => ''
            ];


            $payLogic->changeAlipayStatusByType($test['type'],$value_id,1,'店铺test分账成功');

        } else {
            $cause = $result->sub_msg . '//余额关闭';
            $payLogic->changeAlipayStatusByType($test['type'],$value_id,2,$cause);
            $data = [
                'code' => 0,
                'msg' => '分账失败',
                'data' => $result
            ];
        }
    }


    /**************** 以下可删除 ******************/
    public function test(){
        $data = \Home\Model\PtdataModel::getTdRate('hbtd');
        dump($data);
    }

    public function testredis(){
        $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);

        $hb = \Home\Logic\PayLogic::getRedisKeyByType(2);
        $xyk = \Home\Logic\PayLogic::getRedisKeyByType(1);
        $waphb = \Home\Logic\PayLogic::getRedisKeyByType(4);
        $dmxyk = \Home\Logic\PayLogic::getRedisKeyByType(5);


        $hb = $redis->lrange($hb,0,-1);
        $xyk = $redis->lrange($xyk,0,-1);
        $waphb = $redis->lrange($waphb,0,-1);
        $dmxyk = $redis->lrange($dmxyk,0,-1);

        dump(['hb' => $hb, 'xyk' => $xyk,'waphb' => $waphb, 'dmxyk' => $dmxyk]);
    }

    public function testredisadd(){
        $pass = I('pass');
        $type = I('get.type');
        $value = I('get.value');
        if($pass != 123) {echo "不对啊";exit;}

        $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);

        $key = \Home\Logic\PayLogic::getRedisKeyByType($type);

        $redis->lpush($key,$value);
        $data = $redis->lrange($key,0,-1);
        dump($data);
    }

    public function delredis(){
        $pass = I('pass');
        $value = I('value');
//        $valueArr = explode(',',$value);
        $pay_type = I('pay_type');
        if($pass != 123) {echo "不对啊";exit;}
        $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
        $rediskey = \Home\Logic\PayLogic::getRedisKeyByType($pay_type);
        $redis->lrem($rediskey,1,$value);

//        foreach($valueArr as $k => $v){
//            $redis->lrem($rediskey,1,$v);
//        }

    }

    public function test11(){
        //信用卡通道使用当面付接口金额阀值
        $xyktdfangzhi =  M('ptdata')->where()->getField('xyktdfangzhi');


        dump($xyktdfangzhi);
    }

    public function test12(){
        $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
        $rediskey = \Home\Logic\PayLogic::getRedisKeyByType(2);

        $redis->rpoplpush($rediskey, $rediskey);

//        $len = $redis->llen($rediskey);
//        $max = $len-1;
//        $rand = rand(0,$max);
        $id = $redis->lindex($rediskey, 0);
        echo $id;
    }

    public function test13(){
        $res  = M('test')->where(['seller_id' => '2088331484187063', 'status' => 1,'is_use' => 0,'type' => 2])->order('id desc')->find();
//        dump($res);exit;
        $payLogic = new \Home\Logic\PayLogic();
        $seller_id = '2088331484187063';
        $type = 2;
        $res = $payLogic->getTestOrder($seller_id,$type);

        dump($res);
    }

    public function test14(){
        $userLogic = new \Home\Logic\UserLogic();
        $userLogic->jiandianwei('64/90/97');
    }

    public function test15(){
        echo getNum(0.08) . "\n";

        echo getNum(10.0253) . "\n";
        echo getNum(0.5) . "\n";
    }


}